// 导入API函数
import * as API from './api.js';

// DOM元素
const loginContainer = document.getElementById('login-container');
const adminContainer = document.getElementById('admin-container');
const loginForm = document.getElementById('login-form');
const loginError = document.getElementById('login-error');
const logoutBtn = document.getElementById('logout-btn');
const currentUser = document.getElementById('current-user');
const menuItems = document.querySelectorAll('.menu-item');
const views = document.querySelectorAll('.view');
const modal = document.getElementById('modal');
const modalTitle = document.getElementById('modal-title');
const modalForm = document.getElementById('modal-form');
const closeModal = document.getElementById('close-modal');
const cancelModal = document.getElementById('cancel-modal');
const submitModal = document.getElementById('submit-modal');
const addArticleBtn = document.getElementById('add-article-btn');
const addBannerBtn = document.getElementById('add-banner-btn');
const usersViewHeader = document.querySelector('#users-view .view-header');
const changePasswordBtn = document.getElementById('change-password-btn');

// 当前编辑的数据ID和类型
let currentEditId = null;
let currentEditType = null;

// 初始化页面
function init() {
    console.log('页面初始化开始...');
    // 检查登录状态
    try {
        console.log('检查登录状态...');
        if (API.isLoggedIn()) {
            console.log('用户已登录，显示管理面板');
            showAdminPanel();
        } else {
            console.log('用户未登录，显示登录面板');
            showLoginPanel();
        }
    } catch (error) {
        console.error('检查登录状态时出错:', error);
        showLoginPanel();
    }

    // 绑定事件监听器
    bindEventListeners();
}

// 显示登录面板
function showLoginPanel() {
    loginContainer.classList.remove('hidden');
    adminContainer.classList.add('hidden');
}

// 显示管理面板
function showAdminPanel() {
    loginContainer.classList.add('hidden');
    adminContainer.classList.remove('hidden');
    
    // 更新当前用户显示
    const userInfo = API.getUserInfo();
    if (userInfo) {
        currentUser.textContent = userInfo.nickname || userInfo.phone;
    }
    
    // 显示默认视图（仪表盘）
    switchView('dashboard');
}

// 切换视图
function switchView(viewId) {
    // 更新菜单项激活状态
    menuItems.forEach(item => {
        if (item.dataset.view === viewId) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });
    
    // 更新视图显示
    views.forEach(view => {
        if (view.id === `${viewId}-view`) {
            view.classList.remove('hidden');
            // 加载视图数据
            loadViewData(viewId);
        } else {
            view.classList.add('hidden');
        }
    });
}

// 加载视图数据
function loadViewData(viewId) {
    switch (viewId) {
        case 'dashboard':
            loadDashboardData();
            break;
        case 'articles':
            loadArticlesData();
            break;
        case 'banners':
            loadBannersData();
            break;
        case 'users':
            loadUsersData();
            break;
        case 'assessments':
            loadAssessmentsData();
            break;
    }
}

// 加载仪表盘数据
async function loadDashboardData() {
    try {
        const stats = await API.getDashboardStats();
        
        document.getElementById('articles-count').textContent = stats.articlesCount;
        document.getElementById('banners-count').textContent = stats.bannersCount;
        document.getElementById('users-count').textContent = stats.usersCount;
        document.getElementById('assessments-count').textContent = stats.assessmentsCount;
        
        // 加载最近活动（这里使用模拟数据，实际应从API获取）
        loadRecentActivities();
    } catch (error) {
        console.error('加载仪表盘数据失败:', error);
        showError('加载数据失败');
    }
}

// 加载最近活动
function loadRecentActivities() {
    const activitiesList = document.getElementById('activities-list');
    activitiesList.innerHTML = '';
    
    // 模拟活动数据
    const activities = [
        { text: '创建了一篇新文章：《如何保护眼睛健康》', time: '今天 10:30' },
        { text: '更新了轮播图顺序', time: '昨天 15:45' },
        { text: '有3位新用户注册', time: '前天 09:20' }
    ];
    
    activities.forEach(activity => {
        const activityItem = document.createElement('div');
        activityItem.className = 'activity-item';
        activityItem.innerHTML = `
            <div>${activity.text}</div>
            <div style="font-size: 12px; color: #6b7280;">${activity.time}</div>
        `;
        activitiesList.appendChild(activityItem);
    });
}

// 加载文章数据
async function loadArticlesData() {
    try {
        const data = await API.getAllArticles();
        const tableBody = document.getElementById('articles-table-body');
        tableBody.innerHTML = '';
        
        if (data.success && data.data && data.data.length > 0) {
            data.data.forEach(article => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${article.id}</td>
                    <td>${article.title}</td>
                    <td>${article.publish_date}</td>
                    <td>${article.created_at}</td>
                    <td>
                        <div class="btn-group">
                            <button class="btn-edit" data-id="${article.id}">编辑</button>
                            <button class="btn-delete" data-id="${article.id}">删除</button>
                        </div>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 绑定编辑和删除按钮事件
            bindArticleButtons();
        } else {
            tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无文章数据</td></tr>';
        }
    } catch (error) {
        console.error('加载文章数据失败:', error);
        showError('加载文章数据失败');
    }
}

// 绑定文章按钮事件
function bindArticleButtons() {
    document.querySelectorAll('.btn-edit[data-id]').forEach(btn => {
        btn.addEventListener('click', () => {
            const articleId = parseInt(btn.dataset.id);
            editArticle(articleId);
        });
    });
    
    document.querySelectorAll('.btn-delete[data-id]').forEach(btn => {
        btn.addEventListener('click', () => {
            const articleId = parseInt(btn.dataset.id);
            deleteArticle(articleId);
        });
    });
}

// 加载轮播图数据
async function loadBannersData() {
    try {
        const data = await API.getAllBanners();
        const tableBody = document.getElementById('banners-table-body');
        tableBody.innerHTML = '';
        
        if (data.success && data.data && data.data.length > 0) {
            data.data.forEach(banner => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${banner.id}</td>
                    <td><img src="${banner.image_url}" class="table-image" alt="轮播图"></td>
                    <td>${banner.link}</td>
                    <td>${banner.order}</td>
                    <td>
                        <div class="btn-group">
                            <button class="btn-edit" data-id="${banner.id}">编辑</button>
                            <button class="btn-delete" data-id="${banner.id}">删除</button>
                        </div>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 绑定编辑和删除按钮事件
            bindBannerButtons();
        } else {
            tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无轮播图数据</td></tr>';
        }
    } catch (error) {
        console.error('加载轮播图数据失败:', error);
        showError('加载轮播图数据失败');
    }
}

// 绑定轮播图按钮事件
function bindBannerButtons() {
    document.querySelectorAll('.btn-edit[data-id]').forEach(btn => {
        btn.addEventListener('click', () => {
            const bannerId = parseInt(btn.dataset.id);
            editBanner(bannerId);
        });
    });
    
    document.querySelectorAll('.btn-delete[data-id]').forEach(btn => {
        btn.addEventListener('click', () => {
            const bannerId = parseInt(btn.dataset.id);
            deleteBanner(bannerId);
        });
    });
}

// 加载用户数据
async function loadUsersData() {
    try {
        const data = await API.getAllUsers();
        const tableBody = document.getElementById('users-table-body');
        tableBody.innerHTML = '';
        
        // 获取当前登录用户信息
        const currentUserInfo = API.getUserInfo();
        
        // 检查是否为超级管理员，如果是则添加"添加管理员"按钮
        if (API.isSuperAdmin() && usersViewHeader) {
            // 先移除已存在的按钮，避免重复添加
            const existingAddAdminBtn = document.getElementById('add-admin-btn');
            if (existingAddAdminBtn) {
                existingAddAdminBtn.remove();
            }
            
            const addAdminBtn = document.createElement('button');
            addAdminBtn.id = 'add-admin-btn';
            addAdminBtn.className = 'btn-add';
            addAdminBtn.innerHTML = '<i class="fas fa-user-plus"></i> 添加管理员';
            addAdminBtn.addEventListener('click', () => {
                openAddAdminModal();
            });
            usersViewHeader.appendChild(addAdminBtn);
        }
        
        if (data.success && data.data && data.data.length > 0) {
            data.data.forEach(user => {
                const row = document.createElement('tr');
                
                // 检查是否为普通管理员且当前用户是超级管理员
                const isNormalAdmin = user.is_admin && (currentUserInfo && currentUserInfo.admin_level === 2);
                
                // 如果是普通管理员且当前是超级管理员，则添加特殊样式和点击事件
                if (isNormalAdmin && user.id !== currentUserInfo.id) {
                    row.className = 'admin-row cursor-pointer';
                    row.dataset.adminId = user.id;
                    row.dataset.adminPhone = user.phone;
                    
                    // 添加点击事件，显示删除确认对话框
                    row.addEventListener('click', function() {
                        const adminId = parseInt(this.dataset.adminId);
                        const adminPhone = this.dataset.adminPhone;
                        
                        if (confirm(`确定要删除管理员 ${adminPhone} 吗？`)) {
                            deleteAdmin(adminId);
                        }
                    });
                }
                
                row.innerHTML = `
                    <td>${user.id}</td>
                    <td>${user.phone}</td>
                    <td>${user.nickname || '-'}</td>
                    <td>${user.is_admin ? '是' : '否'}</td>
                    <td>${user.created_at}</td>
                `;
                tableBody.appendChild(row);
            });
        } else {
            tableBody.innerHTML = '<tr><td colspan="5" style="text-align: center;">暂无用户数据</td></tr>';
        }
    } catch (error) {
        console.error('加载用户数据失败:', error);
        showError('加载用户数据失败');
    }
}

// 删除管理员
async function deleteAdmin(adminId) {
    try {
        // 显示加载状态
        showLoading('正在删除管理员...');
        
        const result = await API.deleteAdmin(adminId);
        
        if (result.success) {
            showSuccess('管理员删除成功');
            // 重新加载用户数据
            loadUsersData();
        } else {
            showError(result.message || '删除管理员失败');
        }
    } catch (error) {
        console.error('删除管理员失败:', error);
        showError('删除管理员失败');
    } finally {
        hideLoading();
    }
}

// 加载评估记录数据
async function loadAssessmentsData() {
    try {
        const data = await API.getAllAssessments();
        const tableBody = document.getElementById('assessments-table-body');
        tableBody.innerHTML = '';
        
        if (data.success && data.data && data.data.length > 0) {
            data.data.forEach(assessment => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${assessment.id}</td>
                    <td>${assessment.user_id || '-'}</td>
                    <td>${assessment.assessment_type}</td>
                    <td>${assessment.cas_score || '-'}</td>
                    <td>${assessment.status}</td>
                    <td>${assessment.created_at}</td>
                    <td>
                        <button class="btn-view" data-id="${assessment.id}">查看</button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
            
            // 绑定查看按钮事件
            bindAssessmentButtons();
        } else {
            tableBody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无评估记录</td></tr>';
        }
    } catch (error) {
        console.error('加载评估记录失败:', error);
        showError('加载评估记录失败');
    }
}

// 绑定评估记录按钮事件
function bindAssessmentButtons() {
    document.querySelectorAll('.btn-view[data-id]').forEach(btn => {
        btn.addEventListener('click', () => {
            const assessmentId = parseInt(btn.dataset.id);
            viewAssessment(assessmentId);
        });
    });
}

// 打开添加管理员模态框
function openAddAdminModal() {
    modalTitle.textContent = '添加普通管理员';
    modalForm.innerHTML = '';
    currentEditId = null;
    currentEditType = 'admin';
    
    // 生成添加管理员表单
    generateAddAdminForm();
    
    modal.classList.remove('hidden');
}

// 打开模态框
function openModal(title, type, data = null) {
    modalTitle.textContent = title;
    modalForm.innerHTML = '';
    currentEditId = data ? data.id : null;
    currentEditType = type;
    
    // 根据类型生成表单
    if (type === 'article') {
        generateArticleForm(data);
    } else if (type === 'banner') {
        generateBannerForm(data);
    } else if (type === 'assessment') {
        generateAssessmentForm(data);
    } else if (type === 'password') {
        generatePasswordForm();
    }
    
    modal.classList.remove('hidden');
}

// 生成密码修改表单
function generatePasswordForm() {
    modalForm.innerHTML = `
        <div class="form-group">
            <label for="old-password">当前密码</label>
            <input type="password" id="old-password" name="old-password" required>
        </div>
        <div class="form-group">
            <label for="new-password">新密码</label>
            <input type="password" id="new-password" name="new-password" required>
        </div>
        <div class="form-group">
            <label for="confirm-password">确认新密码</label>
            <input type="password" id="confirm-password" name="confirm-password" required>
        </div>
    `;
}

// 打开密码修改模态框
function openChangePasswordModal() {
    openModal('修改密码', 'password');
}

// 关闭模态框
function closeModalHandler() {
    modal.classList.add('hidden');
    modalForm.reset();
    currentEditId = null;
    currentEditType = null;
}

// 生成文章表单
function generateArticleForm(data = null) {
    modalForm.innerHTML = `
        <div class="form-group">
            <label for="article-title">标题</label>
            <input type="text" id="article-title" name="title" value="${data ? data.title : ''}" required>
        </div>
        <div class="form-group">
            <label for="article-summary">摘要</label>
            <textarea id="article-summary" name="summary" required>${data ? data.summary : ''}</textarea>
        </div>
        <div class="form-group">
            <label for="article-content">内容</label>
            <textarea id="article-content" name="content" required>${data ? data.content : ''}</textarea>
        </div>
        <div class="form-group">
            <label for="article-cover-image">封面图片URL</label>
            <input type="text" id="article-cover-image" name="cover_image" value="${data ? data.cover_image : ''}">
        </div>
        <div class="form-group">
            <label for="article-image-upload">或上传本地图片</label>
            <div class="file-upload-container">
                <input type="file" id="article-image-upload" name="image_upload" accept="image/*" style="display: none;">
                <label for="article-image-upload" class="file-upload-btn">选择图片</label>
                <span id="selected-file-name" class="selected-file-name">未选择文件</span>
                <button type="button" id="clear-file-btn" class="clear-file-btn hidden">清除</button>
            </div>
        </div>
        <div class="form-group">
            <label for="article-publish-date">发布日期</label>
            <input type="date" id="article-publish-date" name="publish_date" value="${data ? data.publish_date : ''}" required>
        </div>
        <div class="form-note">
            <p><strong>注意事项：</strong></p>
            <ul>
                <li>封面图片建议使用正方形比例（如750x750像素）以获得最佳显示效果</li>
                <li>建议图片尺寸不小于500x500像素，文件大小不超过2MB</li>
                <li>上传图片后，系统会自动填充图片URL到上方输入框</li>
            </ul>
        </div>
    `;
    
    // 添加文件上传样式
    const style = document.createElement('style');
    style.textContent = `
        .file-upload-container {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }
        .file-upload-btn {
            padding: 8px 16px;
            background-color: #0066FF;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .file-upload-btn:hover {
            background-color: #0052CC;
        }
        .selected-file-name {
            flex: 1;
            min-width: 200px;
            padding: 8px 12px;
            background-color: #f5f5f5;
            border-radius: 4px;
            font-size: 14px;
            color: #666;
        }
        .clear-file-btn {
            padding: 6px 12px;
            background-color: #ff4d4f;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        .clear-file-btn:hover {
            background-color: #cf1322;
        }
        .clear-file-btn.hidden {
            display: none;
        }
    `;
    document.head.appendChild(style);
    
    // 获取DOM元素
    const fileInput = document.getElementById('article-image-upload');
    const fileNameDisplay = document.getElementById('selected-file-name');
    const clearFileBtn = document.getElementById('clear-file-btn');
    
    // 监听文件选择变化
    fileInput.addEventListener('change', async function(e) {
        if (this.files && this.files[0]) {
            // 显示已选择的文件名
            fileNameDisplay.textContent = this.files[0].name;
            clearFileBtn.classList.remove('hidden');
            
            try {
                // 显示上传中状态
                showLoading('图片上传中...');
                
                // 调用上传API
                const result = await API.uploadImage(this.files[0]);
                
                if (result.success) {
                    // 上传成功后，将返回的图片URL填入输入框
                    document.getElementById('article-cover-image').value = result.image_url;
                    showSuccess('图片上传成功');
                    
                    // 上传成功的视觉反馈
                    fileNameDisplay.textContent = `✓ 已上传: ${this.files[0].name}`;
                    fileNameDisplay.style.color = '#52c41a'; // 成功绿色
                    const fileUploadBtn = document.querySelector('.file-upload-btn');
                    if (fileUploadBtn) {
                        fileUploadBtn.style.backgroundColor = '#52c41a'; // 成功绿色
                    }
                    
                    // 保持文件选择状态，用户可以选择清除或保留
                } else {
                    showError(result.message || '图片上传失败');
                }
            } catch (error) {
                console.error('图片上传失败:', error);
                showError('图片上传失败');
            } finally {
                hideLoading();
            }
        } else {
            // 用户取消了文件选择
            fileNameDisplay.textContent = '未选择文件';
            fileNameDisplay.style.color = '#666'; // 恢复默认颜色
            const fileUploadBtn = document.querySelector('.file-upload-btn');
            if (fileUploadBtn) {
                fileUploadBtn.style.backgroundColor = '#0066FF'; // 恢复默认蓝色
            }
            clearFileBtn.classList.add('hidden');
        }
    });
    
    // 清除已选文件
    clearFileBtn.addEventListener('click', function() {
        fileInput.value = '';
        fileNameDisplay.textContent = '未选择文件';
        fileNameDisplay.style.color = '#666'; // 恢复默认颜色
        const fileUploadBtn = document.querySelector('.file-upload-btn');
        if (fileUploadBtn) {
            fileUploadBtn.style.backgroundColor = '#0066FF'; // 恢复默认蓝色
        }
        clearFileBtn.classList.add('hidden');
    });
}

// 生成添加管理员表单
function generateAddAdminForm() {
    modalForm.innerHTML = `
        <div class="form-group">
            <label for="admin-phone">手机号</label>
            <input type="tel" id="admin-phone" name="phone" required placeholder="请输入管理员手机号">
        </div>
        <div class="form-group">
            <label for="admin-password">密码</label>
            <input type="password" id="admin-password" name="password" required placeholder="请设置管理员密码">
        </div>
        <div class="form-group">
            <label for="admin-confirm-password">确认密码</label>
            <input type="password" id="admin-confirm-password" name="confirm_password" required placeholder="请再次输入密码">
        </div>
        <div class="form-group">
            <label for="admin-nickname">昵称（可选）</label>
            <input type="text" id="admin-nickname" name="nickname" placeholder="请输入管理员昵称">
        </div>
    `;
}

// 生成轮播图表单
function generateBannerForm(data = null) {
    modalForm.innerHTML = `
        <div class="form-group">
            <label for="banner-image-url">图片URL</label>
            <input type="text" id="banner-image-url" name="image_url" value="${data ? data.image_url : ''}" required>
        </div>
        <div class="form-group">
            <label for="banner-image-upload">或上传本地图片</label>
            <div class="file-upload-container">
                <input type="file" id="banner-image-upload" name="image_upload" accept="image/*" style="display: none;">
                <label for="banner-image-upload" class="file-upload-btn">选择图片</label>
                <span id="selected-banner-file-name" class="selected-file-name">未选择文件</span>
                <button type="button" id="clear-banner-file-btn" class="clear-file-btn hidden">清除</button>
            </div>
        </div>
        <div class="form-group">
            <label for="banner-link">链接（可选）</label>
            <input type="text" id="banner-link" name="link" value="${data ? data.link : ''}">
        </div>
        <div class="form-group">
            <label for="banner-order">排序</label>
            <input type="number" id="banner-order" name="order" value="${data ? data.order : 0}" required>
        </div>
        <div class="form-note">
            <p><strong>注意事项：</strong></p>
            <ul>
                <li>图片建议使用750x300像素的尺寸以获得最佳显示效果</li>
                <li>确保填写的链接是有效的，否则用户点击后可能无法正常跳转</li>
                <li>添加新的轮播图后，需要刷新页面才能看到最新效果</li>
            </ul>
        </div>
    `;
    
    // 添加文件上传样式
    const style = document.createElement('style');
    style.textContent = `
        .file-upload-container {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }
        .file-upload-btn {
            padding: 8px 16px;
            background-color: #0066FF;
            color: white;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .file-upload-btn:hover {
            background-color: #0052CC;
        }
        .selected-file-name {
            flex: 1;
            min-width: 200px;
            padding: 8px 12px;
            background-color: #f5f5f5;
            border-radius: 4px;
            font-size: 14px;
            color: #666;
        }
        .clear-file-btn {
            padding: 6px 12px;
            background-color: #ff4d4f;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        .clear-file-btn:hover {
            background-color: #cf1322;
        }
        .clear-file-btn.hidden {
            display: none;
        }
    `;
    document.head.appendChild(style);
    
    // 获取DOM元素
    const fileInput = document.getElementById('banner-image-upload');
    const fileNameDisplay = document.getElementById('selected-banner-file-name');
    const clearFileBtn = document.getElementById('clear-banner-file-btn');
    
    // 监听文件选择变化
    fileInput.addEventListener('change', async function(e) {
        if (this.files && this.files[0]) {
            // 显示已选择的文件名
            fileNameDisplay.textContent = this.files[0].name;
            clearFileBtn.classList.remove('hidden');
            
            try {
                // 显示上传中状态
                showLoading('图片上传中...');
                
                // 调用上传API
                const result = await API.uploadImage(this.files[0]);
                
                if (result.success) {
                    // 上传成功后，将返回的图片URL填入输入框
                    document.getElementById('banner-image-url').value = result.image_url;
                    showSuccess('图片上传成功');
                    
                    // 上传成功的视觉反馈
                    fileNameDisplay.textContent = `✓ 已上传: ${this.files[0].name}`;
                    fileNameDisplay.style.color = '#52c41a'; // 成功绿色
                    const fileUploadBtn = document.querySelector('.file-upload-btn');
                    if (fileUploadBtn) {
                        fileUploadBtn.style.backgroundColor = '#52c41a'; // 成功绿色
                    }
                    
                    // 保持文件选择状态，用户可以选择清除或保留
                } else {
                    showError(result.message || '图片上传失败');
                }
            } catch (error) {
                console.error('图片上传失败:', error);
                showError('图片上传失败');
            } finally {
                hideLoading();
            }
        } else {
            // 用户取消了文件选择
            fileNameDisplay.textContent = '未选择文件';
            fileNameDisplay.style.color = '#666'; // 恢复默认颜色
            const fileUploadBtn = document.querySelector('.file-upload-btn');
            if (fileUploadBtn) {
                fileUploadBtn.style.backgroundColor = '#0066FF'; // 恢复默认蓝色
            }
            clearFileBtn.classList.add('hidden');
        }
    });
    
    // 清除已选文件
    clearFileBtn.addEventListener('click', function() {
        fileInput.value = '';
        fileNameDisplay.textContent = '未选择文件';
        fileNameDisplay.style.color = '#666'; // 恢复默认颜色
        const fileUploadBtn = document.querySelector('.file-upload-btn');
        if (fileUploadBtn) {
            fileUploadBtn.style.backgroundColor = '#0066FF'; // 恢复默认蓝色
        }
        clearFileBtn.classList.add('hidden');
    });
}

// 生成评估记录详情表单
function generateAssessmentForm(data) {
    modalForm.innerHTML = `
        <div class="form-group">
            <label>ID</label>
            <input type="text" value="${data.id}" disabled>
        </div>
        <div class="form-group">
            <label>用户ID</label>
            <input type="text" value="${data.user_id || '-'}" disabled>
        </div>
        <div class="form-group">
            <label>评估类型</label>
            <input type="text" value="${data.assessment_type}" disabled>
        </div>
        <div class="form-group">
            <label>眼皮征</label>
            <input type="text" value="${data.eyelid_sign || '-'}" disabled>
        </div>
        <div class="form-group">
            <label>右眼突出度</label>
            <input type="text" value="${data.right_eye_protrusion || '-'}" disabled>
        </div>
        <div class="form-group">
            <label>左眼突出度</label>
            <input type="text" value="${data.left_eye_protrusion || '-'}" disabled>
        </div>
        <div class="form-group">
            <label>眼球运动</label>
            <input type="text" value="${data.eye_movement || '-'}" disabled>
        </div>
        <div class="form-group">
            <label>CAS评分</label>
            <input type="text" value="${data.cas_score || '-'}" disabled>
        </div>
        <div class="form-group">
            <label>治疗建议</label>
            <textarea disabled>${data.treatment_advice || '-'}</textarea>
        </div>
        <div class="form-group">
            <label>状态</label>
            <select id="assessment-status" name="status">
                <option value="pending" ${data.status === 'pending' ? 'selected' : ''}>待处理</option>
                <option value="processing" ${data.status === 'processing' ? 'selected' : ''}>处理中</option>
                <option value="completed" ${data.status === 'completed' ? 'selected' : ''}>已完成</option>
            </select>
        </div>
    `;
}

// 提交模态框表单
async function submitModalForm(e) {
    e.preventDefault();
    
    try {
        if (currentEditType === 'article') {
            await submitArticleForm();
        } else if (currentEditType === 'banner') {
            await submitBannerForm();
        } else if (currentEditType === 'assessment') {
            await submitAssessmentForm();
        } else if (currentEditType === 'admin') {
            await submitAddAdminForm();
        } else if (currentEditType === 'password') {
            await submitPasswordForm();
        }
        
        closeModalHandler();
        // 重新加载当前视图数据
        const activeView = document.querySelector('.menu-item.active').dataset.view;
        loadViewData(activeView);
        
        showSuccess('操作成功');
    } catch (error) {
        console.error('提交表单失败:', error);
        showError(error.message || '操作失败');
    }
}

// 提交添加管理员表单
async function submitAddAdminForm() {
    const phone = document.getElementById('admin-phone').value;
    const password = document.getElementById('admin-password').value;
    const confirmPassword = document.getElementById('admin-confirm-password').value;
    const nickname = document.getElementById('admin-nickname').value;
    
    // 验证表单
    if (!phone) {
        showError('请输入手机号');
        return;
    }
    
    if (!password) {
        showError('请输入密码');
        return;
    }
    
    if (password !== confirmPassword) {
        showError('两次输入的密码不一致');
        return;
    }
    
    // 构造管理员数据
    const adminData = {
        phone,
        password,
        nickname: nickname || `管理员${phone.slice(-4)}`
    };
    
    // 提交请求
    submitModal.disabled = true;
    submitModal.textContent = '提交中...';
    
    try {
        const result = await API.addNormalAdmin(adminData);
        
        if (result.success) {
            showSuccess('管理员添加成功');
            closeModalHandler();
            // 重新加载用户数据
            loadUsersData();
        } else {
            showError(result.message || '添加管理员失败');
        }
    } catch (error) {
        showError(error.message || '添加管理员失败');
    } finally {
        submitModal.disabled = false;
        submitModal.textContent = '提交';
    }
}

// 提交文章表单
async function submitArticleForm() {
    const formData = {
        title: document.getElementById('article-title').value,
        summary: document.getElementById('article-summary').value,
        content: document.getElementById('article-content').value,
        cover_image: document.getElementById('article-cover-image').value,
        publish_date: document.getElementById('article-publish-date').value
    };
    
    if (currentEditId) {
        await API.updateArticle(currentEditId, formData);
    } else {
        await API.createArticle(formData);
    }
}

// 提交轮播图表单 - 更新于2025-08-26，修复link变量声明问题
async function submitBannerForm() {
    const imageUrl = document.getElementById('banner-image-url').value;
    let link = document.getElementById('banner-link').value;
    const order = parseInt(document.getElementById('banner-order').value);
    
    // 验证必填字段
    if (!imageUrl) {
        throw new Error('请输入图片URL或上传图片');
    }
    
    // 链接是可选的，如果未提供则设置为空字符串
    if (!link) {
        link = '';
    }
    
    const formData = {
        image_url: imageUrl,
        link: link,
        order: order
    };
    
    if (currentEditId) {
        await API.updateBanner(currentEditId, formData);
    } else {
        await API.createBanner(formData);
    }
}

// 提交评估记录表单
async function submitAssessmentForm() {
    const status = document.getElementById('assessment-status').value;
    await API.updateAssessmentStatus(currentEditId, status);
}

// 提交密码修改表单
async function submitPasswordForm() {
    const oldPassword = document.getElementById('old-password').value;
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    
    // 验证新密码和确认密码是否一致
    if (newPassword !== confirmPassword) {
        throw new Error('两次输入的新密码不一致');
    }
    
    // 验证密码长度
    if (newPassword.length < 6) {
        throw new Error('新密码长度至少为6位');
    }
    
    showLoading('修改密码中...');
    try {
        await API.changeAdminPassword(oldPassword, newPassword);
    } finally {
        hideLoading();
    }
}

// 编辑文章
async function editArticle(articleId) {
    try {
        // 获取文章详情（在实际项目中应该有单独的API获取详情）
        const data = await API.getAllArticles();
        const article = data.data.find(a => a.id === articleId);
        
        if (article) {
            openModal('编辑文章', 'article', article);
        } else {
            showError('文章不存在');
        }
    } catch (error) {
        console.error('获取文章详情失败:', error);
        showError('获取文章详情失败');
    }
}

// 删除文章
async function deleteArticle(articleId) {
    if (confirm('确定要删除这篇文章吗？')) {
        try {
            await API.deleteArticle(articleId);
            loadArticlesData();
            showSuccess('文章删除成功');
        } catch (error) {
            console.error('删除文章失败:', error);
            showError(error.message || '删除文章失败');
        }
    }
}

// 编辑轮播图
async function editBanner(bannerId) {
    try {
        // 获取轮播图详情
        const data = await API.getAllBanners();
        const banner = data.data.find(b => b.id === bannerId);
        
        if (banner) {
            openModal('编辑轮播图', 'banner', banner);
        } else {
            showError('轮播图不存在');
        }
    } catch (error) {
        console.error('获取轮播图详情失败:', error);
        showError('获取轮播图详情失败');
    }
}

// 删除轮播图
async function deleteBanner(bannerId) {
    if (confirm('确定要删除这个轮播图吗？')) {
        try {
            await API.deleteBanner(bannerId);
            loadBannersData();
            showSuccess('轮播图删除成功');
        } catch (error) {
            console.error('删除轮播图失败:', error);
            showError(error.message || '删除轮播图失败');
        }
    }
}

// 查看评估记录
async function viewAssessment(assessmentId) {
    try {
        // 获取评估记录详情
        const data = await API.getAllAssessments();
        const assessment = data.data.find(a => a.id === assessmentId);
        
        if (assessment) {
            openModal('评估记录详情', 'assessment', assessment);
        } else {
            showError('评估记录不存在');
        }
    } catch (error) {
        console.error('获取评估记录详情失败:', error);
        showError('获取评估记录详情失败');
    }
}

// 显示成功消息
function showSuccess(message) {
    const notification = document.createElement('div');
    notification.className = 'notification success';
    notification.textContent = message;
    document.body.appendChild(notification);
    
    // 3秒后自动消失
    setTimeout(() => {
        notification.classList.add('fade-out');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}

// 显示错误消息
function showError(message) {
    const notification = document.createElement('div');
    notification.className = 'notification error';
    notification.textContent = message;
    document.body.appendChild(notification);
    
    // 3秒后自动消失
    setTimeout(() => {
        notification.classList.add('fade-out');
        setTimeout(() => {
            notification.remove();
        }, 300);
    }, 3000);
}

// 显示加载中提示
function showLoading(message = '加载中...') {
    // 检查是否已经有loading元素
    let loadingElement = document.getElementById('loading-overlay');
    if (!loadingElement) {
        loadingElement = document.createElement('div');
        loadingElement.id = 'loading-overlay';
        loadingElement.className = 'loading-overlay';
        loadingElement.innerHTML = `
            <div class="loading-content">
                <div class="loading-spinner"></div>
                <p>${message}</p>
            </div>
        `;
        document.body.appendChild(loadingElement);
    }
}

// 隐藏加载中提示
function hideLoading() {
    const loadingElement = document.getElementById('loading-overlay');
    if (loadingElement) {
        loadingElement.remove();
    }
}

// 绑定事件监听器
function bindEventListeners() {
    console.log('绑定事件监听器...');
    console.log('isLoggedIn函数存在:', typeof API.isLoggedIn === 'function');
    console.log('当前登录状态:', API.isLoggedIn());
    
    // 登录表单提交
    loginForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const phone = document.getElementById('phone').value;
        const password = document.getElementById('password').value;
        console.log('尝试登录，手机号:', phone);
        
        try {
            console.log('调用adminLogin函数...');
            const result = await API.adminLogin(phone, password);
            console.log('登录结果:', result);
            
            if (result.success) {
                console.log('登录成功，准备显示管理面板');
                console.log('登录后Token:', API.getToken());
                console.log('登录后UserInfo:', API.getUserInfo());
                
                showAdminPanel();
                console.log('管理面板显示后 - 检查登录状态:', API.isLoggedIn());
                loginForm.reset();
                loginError.textContent = '';
            } else {
                loginError.textContent = result.message || '登录失败';
            }
        } catch (error) {
            console.error('登录异常:', error);
            loginError.textContent = error.message || '登录失败，请检查网络或稍后重试';
        }
    });
    
    // 退出登录
    logoutBtn.addEventListener('click', () => {
        API.removeToken();
        API.removeUserInfo();
        showLoginPanel();
    });
    
    // 菜单项点击
    menuItems.forEach(item => {
        item.addEventListener('click', () => {
            switchView(item.dataset.view);
        });
    });
    
    // 模态框事件
    closeModal.addEventListener('click', closeModalHandler);
    cancelModal.addEventListener('click', closeModalHandler);
    modal.addEventListener('click', (e) => {
        if (e.target === modal) {
            closeModalHandler();
        }
    });
    modalForm.addEventListener('submit', (e) => {
        e.preventDefault();
        submitModalForm();
    });
    // 为提交按钮添加点击事件
    submitModal.addEventListener('click', submitModalForm);
    
    // 修改密码按钮点击
    if (changePasswordBtn) {
        changePasswordBtn.addEventListener('click', openChangePasswordModal);
    } else {
        // 如果页面上没有修改密码按钮，在用户信息旁边添加一个
        const userInfoContainer = currentUser.parentElement;
        const passwordBtn = document.createElement('button');
        passwordBtn.id = 'change-password-btn';
        passwordBtn.className = 'btn-change-password';
        passwordBtn.innerHTML = '<i class="fas fa-key"></i> 修改密码';
        passwordBtn.addEventListener('click', openChangePasswordModal);
        userInfoContainer.appendChild(passwordBtn);
    }
    
    // 添加文章按钮
    addArticleBtn.addEventListener('click', () => {
        openModal('添加文章', 'article');
    });
    
    // 添加轮播图按钮
    addBannerBtn.addEventListener('click', () => {
        openModal('添加轮播图', 'banner');
    });
}

// 初始化应用
init();